package com.kaer.plugin.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;

import com.kaer.plugin.R;
import com.kaer.plugin.utils.JSONKeys;
import com.kaer.plugin.utils.NetworkUtil;
import com.kaer.plugin.utils.SharedConfig;
import com.kaer.plugin.utils.ToastFactory;
import com.kaer.sdk.DeviceInfo;
import com.kaer.sdk.OnClientCallback;
import com.kaer.sdk.serial.SerialReadClient;
import com.kaer.sdk.serial.update.UpdateArmHelper;
import com.kaer.sdk.utils.CardCode;
import com.kaer.sdk.utils.LogUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lizj on 2016/11/15.
 */

public class MainActivity extends AppCompatActivity implements OnClientCallback {
    private String TAG = getClass().getSimpleName();
    @BindView(R.id.btnGetVersion)
    Button btnGetVersion;
    @BindView(R.id.btnCheckUpdate)
    Button btnCheckUpdate;
    @BindView(R.id.tvResult)
    TextView tvResult;
    private ProgressDialog progressDialog;
    private SerialReadClient mClient;
    private final int DELAY = 10000;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UpdateArmHelper.UPDATE_SUCCESS:
                    SharedConfig.getInstance(MainActivity.this).writelongData(JSONKeys.Plugin.LAST_UPDATE, System.currentTimeMillis());
                    LogUtils.e("UPDATE_SUCCESS");
                    if (progressDialog != null) {
                        progressDialog.setProgress(99);
                        progressDialog.setMessage("单片机软件下发成功，正在重启");
                    }
                    mHandler.sendEmptyMessageDelayed(DELAY, DELAY);
                    break;
                case UpdateArmHelper.UPDATE_ERROR:
                    LogUtils.e("更新失败 " + msg.obj.toString());
                    if (msg.obj != null)
                        tvResult.setText("操作结束 " + msg.obj.toString());
                    dismissDialog();
                    changeBtnStatus(true);
                    break;
                case DELAY:
                    LogUtils.e("更新成功");
                    dismissDialog();
                    tvResult.setText("单片机升级结束");
                    changeBtnStatus(true);
                    break;
                default:
                    break;
            }
            mClient.closeSerailPort();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mClient = SerialReadClient.getInstance();
        mClient.setClientCallback(this);
    }

    @OnClick(R.id.btnGetVersion)
    void getVersion() {
        try {
            tvResult.setText(null);
            changeBtnStatus(false);
            int ret = mClient.openSerialPort();
            if (ret == CardCode.KT8000_Success) {
                DeviceInfo info = mClient.getDeviceInfo();
                tvResult.setText(info.toString());
                mClient.closeSerailPort();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            changeBtnStatus(true);
        }
    }

    @OnClick(R.id.btnCheckUpdate)
    void checkUpdate() {
        if (NetworkUtil.isAvailable(this)) {
            try {
                tvResult.setText(null);
                changeBtnStatus(false);
                int ret = mClient.openSerialPort();
                if (ret == CardCode.KT8000_Success) {
                    showDialog();
                    try {
                        mClient.checkUpdate(MainActivity.this, mHandler);
                    } catch (Exception e) {
                        e.printStackTrace();
                        dismissDialog();
                        changeBtnStatus(true);

                    }
//                    new UpdateTask().execute();
                }
            } catch (Exception e) {
                e.printStackTrace();
                changeBtnStatus(true);
            }
        } else {
            ToastFactory.getToast(MainActivity.this, "请检查网络设置").show();
        }
    }

    private void changeBtnStatus(boolean flag) {
        btnGetVersion.setEnabled(flag);
        btnCheckUpdate.setEnabled(flag);
    }


    private void showDialog() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        // 设置ProgressDialog 提示信息
        progressDialog.setMessage("升级中，请勿操作");
        // 设置ProgressDialog 进度条进度
        progressDialog.setMax(100);
        // 设置ProgressDialog 的进度条是否不明确
        progressDialog.setIndeterminate(false);
        // 设置ProgressDialog 是否可以按退回按键取消
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    public void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    public void preExcute(long l) {

    }

    @Override
    public void updateProgress(int i) {
        LogUtils.i(TAG + " updateProgress " + i);
        if (progressDialog != null && progressDialog.isShowing()) {
            LogUtils.i(TAG + " updateProgress isShowing" + i);
            progressDialog.setProgress(i);
        }
    }

    @Override
    public void onConnectChange(int i) {

    }
}
